package minicat.coyote.components;

import minicat.catalina.components.Engine;
import minicat.catalina.components.Server;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicReference;

public class CoyoteAdapter{

    public static void mapping(Server server, Request request, Response response) throws IOException {
        AtomicReference<Boolean> isMatchServlet = new AtomicReference<>(false);
        AtomicReference<Boolean> isMatchStatic = new AtomicReference<>(false);
        server.getServices().stream().forEach(service -> {
            Engine engine = service.getEngine();
            Boolean isMatchHost = engine.getDefaultHost().equals(request.getHost());
            engine.getHosts().stream().forEach(host -> {
                if(isMatchHost || host.getName().equals(request.getHost())){
                    host.getContexts().stream().forEach(context -> {
                        if(context.getPath().equals(request.getPath())){
                            context.getWrappers().stream().forEach(wrapper -> {
                                if(request.getUrl().indexOf(wrapper.getUrlPattern()) == 0){
                                    try {
                                        isMatchServlet.set(true);
                                        wrapper.getServlet().service(request,response);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                };
                            });
                        }
                    });
                }
            });
        });
        if(!isMatchServlet.get()){
            server.getServices().stream().forEach(service -> {
                Engine engine = service.getEngine();
                Boolean isMatchHost = engine.getDefaultHost().equals(request.getHost());
                engine.getHosts().stream().forEach(host -> {
                    if(isMatchHost || host.getName().equals(request.getHost())) {
                        host.getContexts().stream().forEach(context -> {
                            if (request.getUrl().indexOf(context.getPath()) == 0) {
                                try {
                                    isMatchStatic.set(true);
                                    response.outputHtml(context.getDocBase() + request.getUrl().split(context.getPath())[1]);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                });
            });
        }
        if(!isMatchServlet.get() && !isMatchStatic.get()){
            response.outputHtml("404");
        }
    }
}
